package com.moyuaninfo.myyserver.framework.config;

import com.google.common.collect.Sets;
import com.moyuaninfo.myyserver.framework.enums.JsonResultEnum;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.xml.validation.Schema;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author auto
 * @version 1.0
 */
@Configuration
@EnableSwagger2
@ComponentScan(basePackages = {"com.moyuaninfo.*"})
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        //添加全局响应状态码
        List<ResponseMessage> responseMessageList = new ArrayList<>();
        Arrays.stream(JsonResultEnum.values()).forEach(errorEnums -> {
            responseMessageList.add(
                    new ResponseMessageBuilder().code(errorEnums.getCode()).message(errorEnums.getMsg()).responseModel(
                            new ModelRef(errorEnums.getModelRef())).build()
            );
        });

        return new Docket(DocumentationType.SWAGGER_2)
                // 添加全局响应状态码
                .globalResponseMessage(RequestMethod.GET, responseMessageList)
                .globalResponseMessage(RequestMethod.POST, responseMessageList)
                .globalResponseMessage(RequestMethod.PUT, responseMessageList)
                .globalResponseMessage(RequestMethod.DELETE, responseMessageList)
                //协议，http或https
                .protocols(Sets.newHashSet("https", "http"))
                .apiInfo(apiInfo())
                .select()
                //一定要写对，会在这个路径下扫描controller定义
                .apis(RequestHandlerSelectors.basePackage("com.moyuaninfo.myyserver.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("智慧河道接口定义")
                .version("1.0")
                .description("用于测试 API")
                .build();
    }
}
